<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Middleware\Auth;

use Hyperf\Redis\Redis;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as Response;
use Hyperf\HttpServer\Contract\RequestInterface;

class TokenBucketMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container, Response $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //令牌桶限流
        $redis = $this->container->get(Redis::class);
        if($redis->rPop('tokenList')){
            echo 'TokenList length:'.$redis->lLen('tokenList').PHP_EOL;

            return $handler->handle($request);
        }else{
            echo 'TokenList is empty'.PHP_EOL;
            $result = [
                'code' => 0,
                'msg' => '服务器太忙请稍后再试'
            ];
            return $this->response->json($result);
        }

    }
}